package bma.common.netty.telnetserver.common;

import java.net.SocketAddress;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFutureListener;

import bma.common.langutil.core.StringUtil;
import bma.common.langutil.jmshell.JMShellUtil;
import bma.common.langutil.jmshell.common.AbstractSession;
import bma.common.netty.telnetserver.SessionRealm;

public abstract class  CommonTelnetSession extends AbstractSession implements
		SessionRealm {

	protected Channel channel;

	public CommonTelnetSession(String id, Channel channel) {
		super();
		this.id = id;
		this.channel = channel;
	}

	public Channel getChannel() {
		return channel;
	}

	@Override
	public Object getAttribute(String name) {
		if (StringUtil.equals(name, JMShellUtil.SESSION_KEY_REMOTE_IP)) {
			if (channel != null) {
				SocketAddress addr = channel.getRemoteAddress();
				if (addr != null)
					return addr.toString();
			}
		}
		return super.getAttribute(name);
	}

	@Override
	public boolean write(String msg) {
		if (channel != null && channel.isOpen()) {
			channel.write(msg);
			return true;
		}
		return false;
	}

	@Override
	public void close() {
		if (channel != null && channel.isOpen()) {
			channel.write("").addListener(ChannelFutureListener.CLOSE);
		}
	}

	@Override
	public void onClose() {
		invokeClose();
	}

}
